package com.ycj.entropy;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.xuexiang.xui.widget.edittext.MultiLineEditText;
import com.ycj.entropy.data.DaoFactory;
import com.ycj.entropy.data.Study;
import com.ycj.entropy.data.StudyDao;
import com.ycj.entropy.util.CameraUtil;
import com.ycj.entropy.util.DateUtil;
import com.ycj.entropy.util.StringUtil;

import java.util.HashMap;

public class CreateStudyActivity extends Activity {
    private LinearLayout layoutPhotos;
    private View btnAddPhoto;
    private View btnConfirm;
    private View btnCancel;
    private View btnGetLocation;
    private EditText txtTime;
    private EditText txtAddress;
    private EditText txtTitle;
    private MultiLineEditText txtContent;

    private HashMap<ImageView, String> pictures = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_study);
        init();
    }

    /**
     * Callback of camera
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (CameraUtil.TACKING_PICTURE_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
            Bitmap imageBitmap = CameraUtil.getImageThumbnail(CreateStudyActivity.this);
            ImageView imageView = new ImageView(CreateStudyActivity.this);
            imageView.setImageBitmap(imageBitmap);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(dip2px(100f), dip2px(100f)));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(5, 25, 5, 25);
            this.pictures.put(imageView, CameraUtil.getFilename());
            this.layoutPhotos.addView(imageView);
        }
    }

    private void init() {
        this.btnAddPhoto = findViewById(R.id.btn_add_photo);
        this.btnConfirm = findViewById(R.id.btn_confirm);
        this.btnCancel = findViewById(R.id.btn_cancel);
        this.btnGetLocation = findViewById(R.id.btn_get_location);
        this.txtTime = findViewById(R.id.txt_time);
        this.txtAddress = findViewById(R.id.txt_address);
        this.txtContent = findViewById(R.id.txt_content);
        this.txtTitle = findViewById(R.id.txt_title);
        this.layoutPhotos = findViewById(R.id.layout_photos);

        this.btnAddPhoto.setOnClickListener(v -> CameraUtil.takePicture(CreateStudyActivity.this));
        this.btnConfirm.setOnClickListener(v -> confirm());
        this.btnCancel.setOnClickListener(v -> back());
        this.btnGetLocation.setOnClickListener(v -> getLocation());

        this.txtTime.setText(DateUtil.now());

        if(ContextCompat.checkSelfPermission(CreateStudyActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(CreateStudyActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},200);
        }else{
            getLocation();
        }
    }


    private void getLocation() {
        Log.i("", "start to get location");
        TencentLocationManager instance = TencentLocationManager.getInstance(this);
        instance.requestSingleFreshLocation(null, new TencentLocationListener() {
            @Override
            public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
                Log.i("", s);
                CreateStudyActivity.this.txtAddress.setText(tencentLocation.getAddress());
            }

            @Override
            public void onStatusUpdate(String s, int i, String s1) {
                Log.i(s1, s);

            }
        }, Looper.getMainLooper());
    }


    private void confirm() {
        DaoFactory.init(CreateStudyActivity.this);
        StudyDao studyDao = DaoFactory.studyDao();
        Study study = getStudy();
        if (!check(study)) return;
        studyDao.insert(study);
        CameraUtil.saveFiles(CreateStudyActivity.this, study.imageList());
        Toast.makeText(CreateStudyActivity.this, "create success", Toast.LENGTH_SHORT).show();
        back();
    }

    private boolean check(Study study) {
        if (StringUtil.empty(study.getTitle())) {
            Toast.makeText(CreateStudyActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void back() {
        CreateStudyActivity.this.finish();
    }

    private int dip2px(float dipValue) {
        Resources r = CreateStudyActivity.this.getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
    }

    private Study getStudy() {
        return new Study(
                this.txtTitle.getText().toString(),
                this.txtContent.getContentText(),
                this.pictures.values(),
                DateUtil.toMills(this.txtTime.getText().toString()),
                this.txtAddress.getText().toString()
        );
    }
}